<?php

namespace App\Http\Controllers\Api;

use App\Models\Renting;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class LoginController extends Controller
{
    //接口登录
    public function login(Request $request){
        try {
            $this->validate($request,[
                'username'  => 'required',
                'password'  => 'required'
            ]);
        }catch (\Exception $exception){
            return response()->json(['status' => 1000,'msg' => '账号或密码不能为空'],400);
        }

        //查看对象中可有的方法
        //dump(get_class_methods($bool));
        //auth登录
        $bool = auth()->guard('apiweb')->attempt($request->all());

        if ($bool){ //登录成功 生成token

            //获取用户模型对象
            $userModel = auth()->guard('apiweb')->user();

            //判断接口当天请求次数是否超过2000
            if($userModel->click > env('APINUM')){
                return response()->json(['status' => 1002,'msg' => '当天请求次数超过上限']);
            }

            //生成token 保存服务器一份 客户端返回一份
            $token = $userModel->createToken('api')->accessToken;
            $data = [
                'expire' => 7200,
                'token' =>  $token
            ];
            //让当天请求次数加一 要求数据一致性
            $userModel->increment('click');

            //返回数据
            return response()->json($data);

        }else{
            return response()->json(['status' => 1000,'msg' => '账号或密码不能为空'],401);
        }
    }

    //小程序登录
    public function wxlogin(Request $request){
        $appid = 'wx1e993ec2a318eb71';
        $secret = '9a14616bf61fa0079e1e1e2e750e132e';
        //小程序传过来的
        $code = $request->get('code');

        //请求地址
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $url = sprintf($url,$appid,$secret,$code);
        //向wx服务器发送请求
        $client = new Client(['timeout'=>5,'verify'=>false]);
        $response =$client->get($url);
        $json = (string)$response->getBody();
        //json转数组
        $arr = json_decode($json,true);

        //写入到数据表
        try {
            Renting::create(['openid' => $arr['openid']]);
        }catch (\Exception $exception){
        }

        return $json;


    }
}
